var previewWin;
$(function () {
    $("#list").datagrid({
        method: "get",
        url: getRootPath() + "/mtManage/assets/list_deliveryGrid",
        columns: [[
            {field:'ck',checkbox:true},
            {field: "id", title: "ID", width: 25},
            {field: "type_main_name", title: "类型", width: 100},
            {field: "mt_name", title: "物料名称", width: 100},
            {field: "mt_code", title: "物料编码", width: 80},
            {field: "k3_code", title: "K3编码", width: 110},
            {field: "model", title: "型号", width: 100},
            {field: "sizes", title: "规格参数", width: 100},
            {field: "stockin_num", title: "库存数量", width: 50},
            {field: "delivery_num", title: "出库数量", width: 50},
            {field: "unit", title: "单位", width: 30},
            // {field: "supplier", title: "供应商", width: 50},
            {field: "erp", title: "关联ERP", width: 95},
            {field: "conDept", title: "事业部", width: 95},
            {field: "conProductNum", title: "机型", width: 95},
            {field: "purpose", title: "借出用途", width: 95,
                formatter:function (value,row,index) {
                    if (value == null)
                    {return "";}
                    else
                    {return  "<span title='"+value+"'>"+value+"</span>";}
                }
            },
            {field: "quantity_ret", title: "退回数量", width: 50},
            {field: "remarks", title: "备注", width: 95},
            {field: "delivery_man", title: "出库人", width: 95},
            {field: "delivery_time", title: "出库时间", width: 150,
                //内容悬浮功能
                formatter:function (value,row,index) {
                    return  "<span title='"+value+"'>"+value+"</span>";
                }
            },
            {field: "state", title: "状态", width: 150,
                //内容悬浮功能
                formatter:function (value,row,index) {
                    switch (value) {
                        case 0:return "未确认";
                        case 1:return "已确认";
                        default:return "未知状态";
                    }
                }
            },
            {field: "operation", title: "确认操作", width: 150,
                formatter:function (value,row,index) {
                var names = ['黄晓婷','谢靖','钱意','袁丰','李志伦'];
                if (names.includes(username))
                {
                    if (row.state == 0)
                    {
                        var btn = "<button onclick=\"affirm("+row.id+")\" class=\"button-edit button-green\">确认出库记录</button>";
                        return btn;
                    }else
                    {return "无需进行任何操作";}

                }
                else
                {return "无确认操作权限";}

                }
            }
        ]],
        onDblClickRow:function (index, row) {
            preview(row);
        },
        onLoadSuccess: function (data) {
            $('.button-delete').linkbutton({});
            $('.button-edit').linkbutton({});
        },
        pagination: true,
        striped: true,
        // singleSelect:true,
        //工具条
        toolbar: "#toolbar",
    });

    //点击添加按钮，弹出编辑窗口
    $("#saveBtn").click(function () {
        //将表单清空
        $("#editForm").form("clear");
        //将登录人员赋值
        setVal("#delivery_user",username);
        //打开窗口
        $("#editWin").dialog("open");
    });

    //通过K3编码找到对应信息
    $("#k3Code").textbox('textbox').keydown(function (e) {
        if (e.keyCode == 13) {
            var value = $("input[name='k3Code']").val().trim().toUpperCase();
            $.getJSON(getRootPath() + "/mtManage/assets/mtInfo?k3_code=" + value, function (json) {
                if (json.code == 200) {
                    $("#editForm").form("load", json.data);
                    // $("#stockin_user").textbox({
                    //     value:username
                    // });
                    $.messager.show({
                        title: "提示",
                        msg: "查询成功"
                    });
                } else {
                    $.messager.alert("提示", "未查询到对应数据:" + json.message, "error");
                    $("#editForm").form("clear");
                }
            });
        }
    });

    //通过物料编码找到对应信息
    $("#typeDtlNo").textbox('textbox').keydown(function (e) {
        if (e.keyCode == 13) {
            var value = $("input[name='typeDtlNo']").val().trim().toUpperCase();
            $.getJSON(getRootPath() + "/mtManage/assets/mtInfo?typeDtlNo=" + value, function (json) {
                if (json.code == 200) {
                    $("#editForm").form("load", json.data);
                    // $("#stockin_user").textbox({
                    //     value:username
                    // });
                    $.messager.show({
                        title: "提示",
                        msg: "查询成功"
                    });
                } else {
                    $.messager.alert("提示", "未查询到对应数据:" + json.message, "error");
                    $("#editForm").form("clear");
                }
            });
        }
    });

    //保存商品
    $("#save").click(function () {
        var formUrl;
        if($("input[name='id']").val()==""){
            formUrl=getRootPath() + "/mtManage/assets/addMtDeliveryRecord";
        }else{
            formUrl=getRootPath() + "/mtManage/assets/updateMtDeliveryRecord";
        }
        $("#editForm").form("submit", {
            url:formUrl ,
            onSubmit: function () {
                //表单验证
                return $("#editForm").form("validate");
            },
            success: function (data) {
                // $.messager.alert("提示", "保存失败:" + data, "error");
                data = eval("(" + data + ")");//转成json
                if (data.data=='1') {
                    //1.表单清空
                    $("#editForm").form("clear");
                    //2.关闭窗口
                    $("#editWin").window("close");
                    //3.刷新datagrid
                    $("#list").datagrid("reload");
                    if(formUrl==getRootPath() + "/mtManage/assets/updateMtDeliveryRecord"){
                        $.messager.show({
                            title: "提示",
                            msg: "修改成功"
                        });
                    }else{
                        $.messager.show({
                            title: "提示",
                            msg: "新增成功"
                        });
                    }
                } else {
                    if(formUrl==getRootPath() + "/mtManage/assets/updateMtDeliveryRecord"){
                        if(data.data=='0'){
                            $.messager.alert("提示", "修改失败:库存数量不足", "error");
                        }else if(data.data=='999'){
                            $.messager.alert("提示", "修改失败:不为最后一条记录", "error");
                        }else {
                            $.messager.alert("提示", "修改失败:" + data.message, "error");
                        }
                    }else{
                        if(data.data=='0'){
                            $.messager.alert("提示", "新增失败:库存数量不足", "error");
                        }else {
                            $.messager.alert("提示", "新增失败:" + data.message, "error");
                        }
                    }
                }
            }
        });
    });
    $("#reset").click(function () {
        $("#editForm").form("clear");
    });

    //修改商品 -- 回显商品信息
    $("#editBtn").click(function () {

        //将表单清空
        $("#editForm").form("clear");

        //1.获取选择的商品
        var rows = $("#list").datagrid("getSelections");

        //判断一次只能选择一个
        if (rows.length != 1) {
            $.messager.alert("提示", "一次只能选择一行", "warning");
            return;
        }

        //2.获取第一行
        var row = rows[0];

        //3.到后台商品数据，填充到表单
        $.getJSON(getRootPath() + "/mtManage/assets/deliveryInfo?id=" + row.id, function (json) {
            $("#editForm").form("load", json.data);
        })

        //4.弹出编辑窗口
        $("#editWin").window("open");
    });

    //删除商品
    $("#deleteBtn").click(function () {
        //1.获取选择的商品
        var rows = $("#list").datagrid("getSelections");

        if (rows.length == 0) {
            $.messager.alert("提示", "至少选择一个商品", "warning");
            return;
        }

        //2.获取商品的id 格式： 字符串  1,2,3
        var ids = new Array();
        $(rows).each(function (i) {
            ids.push(rows[i].id);
        });

        ids = ids.join(",");//用逗号进行分隔
        //通过提示框确认是否进行删除
        $.messager.confirm('提示', '确定要删除吗？', function(r){
            if (r){
                //3.发送商品id到后台进行删除
                $.post(getRootPath() + "/mtManage/assets/deleDeliveryInfo", {"ids": ids}, function (data) {
                    //刷新datagrid
                    $("#list").datagrid("reload");
                    //提示
                    $.messager.show({
                        title: "提示",
                        msg: data.message
                    });
                }, "json");
            }
        });
    });
});

function affirm(id) {
    //通过提示框确认是否进行确认操作
    $.messager.confirm('提示', '确定要确认吗，确认后此记录不可修改？', function(r){
        if (r){
            //3.发送商品id到后台进行删除
            $.post(getRootPath() + "/mtManage/assets/ChangeDeliveryState", {"id": id}, function (data) {
                if (data.message=="ok") {
                    //刷新datagrid
                    $("#list").datagrid("reload");
                    //提示
                    $.messager.show({
                        title: "提示",
                        msg: "确认成功"
                    });
                } else {
                    $.messager.show({
                        title: "提示",
                        msg: data.message
                    });
                }
            }, "json");
        }
    });
}

function preview(row) {
    previewWin = $("#previewWin").dialog({
        title: '预览出库记录',
        width: 820,
        height: 480,
        maximizable: false,
        modal: true,
        buttons: [{
            text: '关闭',
            handler: function () {
                previewWin.dialog('close');
            }
        }]
    });

    $("#previewWin_k3Code").text(row.k3_code==null?"":row.k3_code);
    $("#previewWin_typeDtlNo").text(row.mt_code==null?"未知物料编码":'物料编码:'+row.mt_code);
    $("#previewWin_typeMain").text(row.type_main_name==null?"":row.type_main_name);
    $("#previewWin_mtName").text(row.mt_name==null?"":row.mt_name);
    $("#previewWin_model").text(row.model==null?"":row.model);
    $("#previewWin_sizes").text(row.sizes==null?"":row.sizes);
    $("#previewWin_num").text(row.delivery_num==null?"":row.delivery_num);
    $("#previewWin_unit").text(row.unit==null?"":row.unit);
    $("#previewWin_erp").text(row.erp==null?"":row.erp);
    $("#previewWin_conDept").text(row.conDept==null?"":row.conDept);
    $("#previewWin_conProductNum").text(row.conProductNum==null?"":row.conProductNum);
    $("#previewWin_user").text(row.delivery_man==null?"":row.delivery_man);
    $("#previewWin_delivery_time").text(row.delivery_time==null?"":'出库时间:'+row.delivery_time);
    $("#previewWin_quantity_ret").text(row.quantity_ret==null?"":row.quantity_ret);
    $("#previewWin_purpose").html(row.purpose==null?"":row.purpose.toString().replace('\n','<br/>').replace('\r\n','<br/>'));
    $("#previewWin_remarks").html(row.remarks==null?"":row.remarks.toString().replace('\n','<br/>').replace('\r\n','<br/>'));

}

//单元格扩展悬浮显示功能
var columShow = function colum_Show(value,row,index){
    return '<span title='+value+'>'+value+'</span>'
}

// 物资入库查询
function queryDelivery() {
    //console.log($("#stockin_man_s").val());
    $("#list").datagrid('load', {
            type_dtl_no:$("#type_dtl_no").val().trim(),
            k3_code:$("#k3_code").val().trim(),
            delivery_man:$("#delivery_man_s").val().trim()
        }
    );
}

$("#expbtn").click(function() {
    window.location.href=getRootPath() +'/mtManage/assets/exportDelivetyData?type_dtl_no='+$("#type_dtl_no").val().trim()+"&k3_code="+$("#k3_code").val().trim()+"&delivery_man="+$("#delivery_man_s").val().trim();
});